package com.duojuhe.common.utils.idgenerator;

import java.text.*;
import java.util.Calendar;
import java.util.UUID;

/**
 * uuid生成工具类，主要用一些数据表主键生成
 *
 * @date 2018/5/24.
 */
public class UUIDUtils {
    private static final FieldPosition HELPER_POSITION = new FieldPosition(0);

    /**
     * This Format for format the data to special format.
     */
    private final static Format dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * This Format for format the number to special format.
     */
    private final static NumberFormat numberFormat = new DecimalFormat("0000");
    /**
     * 序列
     */
    private static int seq = 0;
    /**
     * 最大值
     */
    private static final int MAX = 999999;

    private static String[] chars = new String[]{
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N",
            "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"};

    /**
     * 获取一个长度为32的uuid
     *
     * @return
     */
    public static synchronized String getUUID32() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    /**
     * 获取一个长度为8的uuid
     */
    public static synchronized String getUUID8() {
        StringBuilder sb = new StringBuilder();
        String uuid = getUUID32();
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            sb.append(chars[x % 0x24]);
        }
        return sb.toString();
    }


    /**
     * 生成序列编号
     *
     * @return
     */
    public static synchronized String getSequenceNo() {
        Calendar rightNow = Calendar.getInstance();
        StringBuffer sb = new StringBuffer();
        dateFormat.format(rightNow.getTime(), sb, HELPER_POSITION);
        numberFormat.format(seq, sb, HELPER_POSITION);
        if (seq == MAX) {
            seq = 0;
        } else {
            seq++;
        }
        return sb.toString();
    }
}
